package com.hunantv.mglive.ui.discovery.publisher.pic;

import android.graphics.Bitmap;
import android.widget.ImageView;

import com.hunantv.mglive.utils.L;

//run in ui thread....
public class ImageDecodeFinishedRunnable implements Runnable {

	private ImageView mImageView;
	private String mImagePath;
	private Bitmap mBitmap;
	private int mDesiredWidth;
	private int mDesiredHeight;

	public ImageDecodeFinishedRunnable(Bitmap bitmap, String imgPath,
			ImageView imgView, int desiredWidth, int desiredHeight) {
		mImageView = imgView;
		mImagePath = imgPath;
		mBitmap = bitmap;
		mDesiredWidth = desiredWidth;
		mDesiredHeight = desiredHeight;
	}

	@Override
	public void run() {

		String imgUrl = (String)mImageView.getTag();
		if(imgUrl == null || !imgUrl.equalsIgnoreCase(mImagePath) )//请求已发生改变。。。
			return;
		
		// 1. set bitmap for imageView
		L.d("img", "setLocalImageBitmap path:" + mImagePath);
		mImageView.setImageBitmap(mBitmap);
		
		// 2.cache bitmap..
		String url = getCacheKey(mImagePath, mDesiredWidth, mDesiredHeight);
		SendImageCache.getInstance().putBitmap(url, mBitmap);
		
		

	}

	/**
	 * Creates a cache key for use with the L1 cache.
	 * 
	 * @param url
	 *            The URL of the request.
	 * @param maxWidth
	 *            The max-width of the output.
	 * @param maxHeight
	 *            The max-height of the output.
	 */
	public static String getCacheKey(String url, int maxWidth, int maxHeight) {
		return new StringBuilder(url.length() + 12).append("#W")
				.append(maxWidth).append("#H").append(maxHeight).append(url)
				.toString();
	}

	public static Bitmap getBitmap(String url, int viewWidth, int viewHeight) {
		
		return SendImageCache.getInstance().getBitmap(
				getCacheKey(url, viewWidth, viewHeight));
	}
}